package com.codecrecord;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Created by android on 8/8/17.
 */

public class MediaMuxerEx {

    private static final String TAG = "fuyao";
    private MediaMuxer mediaMuxer;
    private String mVideoPath;
    private TextureMovieEncoder.OnVideoDone mOnVideoDone;

    private volatile boolean mStarted = false;

    private volatile int mEncoderCount, mStatredCount;
    /**
     * Constructor.
     * Creates a media muxer that writes to the specified path.
     *
     * @param path   The path of the output media file.
     * @param format The format of the output media file.
     * @throws IllegalArgumentException if path is invalid or format is not supported.
     * @throws IOException              if failed to open the file for write.
     */
    public MediaMuxerEx(@NonNull String path, int format, TextureMovieEncoder.OnVideoDone onVideoDone) throws IOException {
        mediaMuxer = new MediaMuxer(path, format);
        mOnVideoDone = onVideoDone;
        mVideoPath = path;
    }

    public void addEncoder() {
        mEncoderCount++;
    }

    public int addTrack(@NonNull MediaFormat format) {
        return mediaMuxer.addTrack(format);
    }

    public void writeSampleData(int trackIndex, @NonNull ByteBuffer byteBuf,
                                @NonNull MediaCodec.BufferInfo bufferInfo) {
        mediaMuxer.writeSampleData(trackIndex, byteBuf, bufferInfo);
    }

    public boolean isStarted() {
        return mStarted;
    }

    /*package*/
    synchronized boolean start() {
        mStatredCount++;
        if (!mStarted && (mEncoderCount > 0) && (mStatredCount == mEncoderCount)) {
            mStarted = true;
            mediaMuxer.start();
            Log.d("fuyao", "mediaMuxer started");
        }
        return mStarted;
    }

    synchronized void stop() {
        Log.v(TAG, "stop:mStatredCount=" + mStatredCount);
        mStatredCount--;
        if ((mEncoderCount > 0) && (mStatredCount <= 0)) {
            try {
                mediaMuxer.stop();
                mediaMuxer.release();
            } catch (final Exception e) {
                Log.w(TAG, e);
            }
            mOnVideoDone.videoDone(mVideoPath);
            mStarted = false;
            mediaMuxer = null;
            Log.v(TAG, "MediaMuxer stopped:");
        }
    }
}
